<template>
  <div>
    <top-nav-bar :applyPageRoute="nowRouteTitle" @back="back"></top-nav-bar>
    <a-card :bordered="false" :bodyStyle="{ padding: '16px', height: '100%' }">
      <div style="margin-left: 44px; margin-top: 20px; min-height: 400px">
        <div class="form-item">
          <span class="title">结算工资：</span>
          <a-input placeholder='如"12月工资"' style="width: 300px" v-model="form.name" />
        </div>
        <div class="form-item">
          <span class="title">结算区间：</span>
          <a-range-picker
            :disabled-date="disabledDate"
            v-model="classTime"
            format="YYYY-MM-DD"
            style="width: 300px"
            @change="rangeChange"
          />
        </div>
        <div class="form-item">
          <span class="title">结算对象：</span>
          <div>
            <a-button @click="open">选择员工</a-button>
            <div style="margin-top: 5px; color: #999" v-if="selectStudent.length > 0">
              已选择 <a>{{ selectStudent.length }}</a
              >人
            </div>
          </div>
        </div>
        <div class="form-item">
          <span class="title">发薪日期：</span>
          <a-date-picker style="width: 300px" @change="faXinDate" />
          <!-- <a-input placeholder='如"12月工资"'  /> -->
        </div>

        <div style="margin-left: 76px">
          <div style="color: #999">本次工资结算将计入此日期的支出记录</div>
          <a-button type="primary" style="margin-top: 10px" @click="finish"> 计算工资 </a-button>
        </div>
      </div>
    </a-card>
    <!-- 选择员工 -->
    <a-modal
      title="选择员工"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
      :width="680"
    >
      <div style="margin-bottom: 16px">
        <a-input-search
          placeholder="搜索员工姓名/手机号(回车搜索)"
          style="width: 250px; margin-right: 24px"
          @search="onSearch"
          v-model="teacherName"
          @pressEnter="onSearch"
        />
        <a-checkbox @change="onChangeSk"> 授课 </a-checkbox>
        <a-checkbox @change="onChangeZZ"> 在职 </a-checkbox>
      </div>
      <a-spin :spinning="spinning">
        <a-table
          :row-selection="{ selectedRowKeys: beforeSelectRowKeys, onChange: onSelectChange }"
          :columns="columns"
          :data-source="data"
          :pagination="false"
          class="user_management_table"
          :scroll="{ y: 340 }"
          style="border:1px solid #e8e8e8;"
        >
          <span slot="is_on_job" slot-scope="text, record">
            {{ record.name }} <span style="margin-left: 5px" v-if="!record.is_on_job">（已离职）</span>
          </span>
          <span slot="is_teaching" slot-scope="text, record">
            {{ record.is_teaching ? '授课' : '不授课' }}
          </span>
        </a-table>
        <div style="margin-top: 28px; display: flex; justify-content: space-between">
          <div>共{{ total }}条数据</div>
          <a-pagination :total="total" @change="changePage" />
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import { accountList } from '@/api/account'
import topNavBar from '@/components/topNavBar/topNavBar'
import { addSettlement } from '@/api/wageSettlement'
export default {
  components: { topNavBar },
  data() {
    return {
      classTime: [],
      form: {
        name: '',
        start_time: '',
        end_time: '',
        user_school_ids: [],
        pay_date: '',
      },
      nowRouteTitle: '',
      visible: false,
      confirmLoading: false,
      columns: [
        {
          title: '员工姓名',
          dataIndex: 'name',
          scopedSlots: { customRender: 'is_on_job' },
        },
        {
          title: '手机号',
          dataIndex: 'phone',
        },
        {
          title: '是否授课',
          scopedSlots: { customRender: 'is_teaching' },
        },
      ],
      data: [],
      beforeSelectRowKeys: [],
      selectedRowKeys: [],
      beforeSelectStudent: [],
      selectStudent: [],
      teacherName: undefined,
      pageNo: 1,
      total: 5,
      school_id: this.$store.state.user.school,
      spinning: false,
      is_on_job: undefined,
      is_teaching: undefined,
    }
  },
  created() {
    this.nowRouteTitle = this.$route.meta.title
    let type = this.$route.params.type //判断从工资条进入 还是从绩效管理进入
    if (type == 2) {
      let { startDay, endDay } = this.getStartDay()
      this.form.start_time = startDay
      this.form.end_time = endDay
      this.$set(this.classTime, 0, moment(startDay))
      this.$set(this.classTime, 1, moment(endDay))
      accountList({
        pageSize: 9999,
        school_id: this.school_id,
      }).then((res) => {
        for (let i = 0; i < 10; i++) {
          this.beforeSelectRowKeys.push(i)
          this.selectedRowKeys.push(i)
        }
        this.selectStudent = res.data
        this.beforeSelectStudent = res.data
        this.selectStudent.forEach((item) => {
          this.form.user_school_ids.push(item.user_school_ids)
        })
      })
    }
    // console.log(a,3);
  },

  methods: {
    //获取本月第一天和最后一天
    getStartDay() {
      let date = moment().startOf('month') //当月第一天
      let y = date.get('year')
      let m = date.get('month') + 1
      let d = date.get('date')
      let startDateString = y + '-' + m + '-' + d

      let date1 = moment().endOf('month') //当月最后一天
      let yy = date1.get('year')
      let mm = date1.get('month') + 1
      let dd = date1.get('date')
      let endDateString = yy + '-' + mm + '-' + dd
      return { startDay: startDateString, endDay: endDateString }
    },
    rangeChange(dateMoment, dateString) {
      this.form.start_time = dateString[0]
      this.form.end_time = dateString[1]
      console.log(this.form)
    },
    disabledDate(current) {
      // Can not select days before today and today
      return current && current > moment().endOf('day')
    },
    faXinDate(m, d) {
      this.form.pay_date = d
      console.log(m, d, '发薪日期', this.form)
    },
    finish() {
      let parmars = JSON.parse(JSON.stringify(this.form))
      parmars.school_id = this.$store.state.user.school
      if (parmars.name == '') {
        this.$message.warning('请填写结算工资')
        return
      }
      if (parmars.end_time == '') {
        this.$message.warning('请选择结算区间')
        return
      }
      if (parmars.user_school_ids.length == 0) {
        this.$message.warning('请选择结算对象')
        return
      }
      if (parmars.pay_date == '') {
        this.$message.warning('请选择发薪日期')
        return
      }
      addSettlement(parmars)
        .then((res) => {
          this.$message.success('添加成功')
          this.back()
        })
        .catch((err) => {
          this.$message.error(err.data.message || '添加失败')
        })
    },
    handleOk() {
      this.selectStudent = this.beforeSelectStudent
      this.selectedRowKeys = this.beforeSelectRowKeys
      this.selectStudent.forEach((item) => {
        this.form.user_school_ids.push(item.user_school_id)
      })
      this.visible = false
    },
    handleCancel() {
      // selectedRowKeys
      if (this.selectedRowKeys.length > 0) {
        this.beforeSelectRowKeys = this.selectedRowKeys
      } else {
        this.beforeSelectRowKeys = []
      }
      this.visible = false
    },
    open(isOpen = true) {
      if (isOpen) {
        this.visible = true
      }
      this.spinning = true
      //差个在职离职条件查询
      accountList({
        keywords: this.teacherName,
        is_on_job: this.is_on_job,
        is_teaching: this.is_teaching,
        pageSize: 10,
        pageNo: this.pageNo,
        school_id: this.school_id,
      })
        .then((res) => {
          this.data = res.data
          this.total = res.meta.pagination.total
        })
        .catch((err) => {})
        .finally(() => {
          this.spinning = false
        })
    },
    changePage(page) {
      this.pageNo = page
      this.open(false)
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.beforeSelectRowKeys = selectedRowKeys
      this.beforeSelectStudent = selectedRows
      console.log(selectedRowKeys, selectedRows, 6)
    },
    onChangeSk(e) {
      console.log(`checked = ${e.target.checked}`)
      if (e.target.checked) {
        this.is_on_job = 1
      } else {
        this.is_on_job = undefined
      }
      this.pageNo = 1
      this.open(false)
    },
    onChangeZZ(e) {
      console.log(`checked = ${e.target.checked}`)
      if (e.target.checked) {
        this.is_teaching = 1
      } else {
        this.is_teaching = undefined
      }
      this.pageNo = 1
      this.open(false)
    },
    onSearch() {
      this.pageNo = 1
      this.open(false)
    },
    back() {
      this.$router.go(-1)
    },
  },
}
</script>

<style lang="less" scoped>
.form-item {
  display: flex;
  margin-bottom: 16px;
  align-items: center;
  .title {
    margin-right: 5px;
  }
}
</style>